package com.zny.sescore.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zny.sescore.model.ApiResult;
import com.zny.sescore.model.PageWrap;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller基类
 *
 * @author zhangnayi
 * @date 2021/03/26 19:48
 */
@Slf4j
public class CurdController<S extends IService<E>, E> extends BaseController {

    @Autowired
    protected S service;

    @PostMapping("/page")
    @ApiOperation("查询分页")
    public ApiResult<IPage<E>> getPage(@RequestBody PageWrap<E> pageWrap) {
        return ApiResult.success(service.page(pageWrap.getPage(), new QueryWrapper<>(pageWrap.getModel())));
    }

    @PostMapping("/get_by_id/{id}")
    @ApiOperation("详情")
    public ApiResult<E> getById(@PathVariable Integer id) {
        return ApiResult.success(service.getById(id));
    }

    @PostMapping("/create")
    @ApiOperation("新建")
    public ApiResult<Boolean> create(@RequestBody E entity) {
        return ApiResult.success(service.save(entity));
    }

    @PostMapping("/update_by_id")
    @ApiOperation("修改")
    public ApiResult<Boolean> updateById(@RequestBody E entity) {
        return ApiResult.success(service.updateById(entity));
    }

    @PostMapping("/delete/{id}")
    @ApiOperation("删除")
    public ApiResult<Boolean> deleteById(@PathVariable Integer id) {
        return ApiResult.success(service.removeById(id));
    }

    @PostMapping("/delete/batch")
    @ApiOperation("批量删除")
    public ApiResult<Boolean> batchDelete(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        if (!idList.isEmpty()) {
            return ApiResult.success(true);
        }
        service.removeByIds(idList);
        return ApiResult.success(true);
    }
}